package com.concurrent.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: zhouyang
 * @descrpition: 修饰代码块
 * @time: 2019-05-04 22:28
 */
@Slf4j
public class SynchronizedTest1 {

    //修饰一个代码块
    public void test1(){
        synchronized (this){
            for(int i=0;i<10;++i){
                log.info("test1 - {}",i);
            }
        }
    }

    //修饰一个代码块 是以类为对象锁
    public void test3(int j){
        synchronized (this){
            for(int i=0;i<10;++i){
                log.info("test{} - {}",j,i);
            }
        }
    }

    //修饰一个方法 以方法为对象锁
    public synchronized void test2(){
        for(int i=0;i<10;++i){
            log.info("test2 - {}",i);
        }
    }

    //修饰一个方法
    public synchronized void test4(int j){
        for(int i=0;i<10;++i){
            log.info("test{} - {}",j,i);
        }
    }

    public static void main(String[] args) {
//        SynchronizedTest1 example = new SynchronizedTest1();

//        ExecutorService executorService = Executors.newCachedThreadPool();
//        executorService.execute(()->{
//            example.test2();//1和2效果一致
//        });
//        executorService.execute(()->{
//            example.test2();
//        });
//        executorService.shutdown();


        SynchronizedTest1 example1 = new SynchronizedTest1();
        SynchronizedTest1 example2 = new SynchronizedTest1();

        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(()->{//先打印1再打印2 因为锁定了方法块
            example1.test3(1);
        });
        executorService.execute(()->{
            example2.test3(2);
        });
        executorService.shutdown();


//        SynchronizedTest1 example1 = new SynchronizedTest1();
//        SynchronizedTest1 example2 = new SynchronizedTest1();
//
//        ExecutorService executorService = Executors.newCachedThreadPool();
//        executorService.execute(()->{
//            example1.test4(1);//0和1交替打印 因为只锁定了方法
//        });
//        executorService.execute(()->{
//            example2.test4(2);
//        });
//        executorService.shutdown();

    }
}
